package com.huacloud.rocketmq;


import org.apache.log4j.Logger;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;

/**
 * Created by hcf on 2017/6/15.
 */
public class SyncProducer {

    private static Logger log = Logger.getLogger(ProducerMain.class);

    private String groupName = null;
    private String nameSrvIp = null;
    private String nameSrvPort = null;
    private String instanceName = null;
    private String topicName = null;
    private String tagname = null;
    DefaultMQProducer producer = null;

    /**
     * @param groupName
     * @param nameSrvIp
     * @param nameSrvPort
     * @param instanceName
     * @param topicName
     * @param tagName
     */
    public SyncProducer(String groupName, String nameSrvIp, String nameSrvPort, String instanceName, String topicName, String tagName) {
        this.groupName = groupName;
        this.nameSrvIp = nameSrvIp;
        this.nameSrvPort = nameSrvPort;
        this.instanceName = instanceName;
        this.topicName = topicName;
        this.tagname = tagName;

        producer = new DefaultMQProducer(groupName);
        producer.setNamesrvAddr(nameSrvIp + ((nameSrvPort.isEmpty()) ? "" : ":" + nameSrvPort));
        producer.setInstanceName(instanceName);
        producer.setVipChannelEnabled(false);

        log.info(producer.getNamesrvAddr());
    }

    /**
     * @return
     */
    public int sendMessage(String message) {

        if (producer == null) {
            return -1;
        }


        try {
            producer.start();
            Message msg = new Message(this.topicName, this.tagname, message.getBytes(RemotingHelper.DEFAULT_CHARSET));

            SendResult sendResult = producer.send(msg);

            System.out.print(sendResult.toString());

            producer.shutdown();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return 0;
    }

    @Override
    public String toString() {
        return "groupName[" + this.groupName + "],nameSrvIp[" + this.nameSrvIp + "],nameSrvPort[" + this.nameSrvPort + "],instanceName[" + this.instanceName + "],topicName[" + this.topicName + "],tagname[" + this.tagname + "]";
    }
}
